import { forwardRef, useImperativeHandle, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, Drawer, Form, Input, Space, Table } from 'antd';

import Filter from '@/components/filter';

import { TimeSort } from '@/enum';
import { inventoryDeviceInfoPage } from '@/services/bizApi/kucunshebaokucunguanlibiaojiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: (arr: BIZAPI.InventoryDeviceInfoEntity[]) => void;
};

export type EquipmentRef = {
  open: (arg: EditOpenBaseArgs) => void;
};

export type EditProps = {};

const Equipment: React.ForwardRefRenderFunction<EquipmentRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EquipmentRef['open']>[0]>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<BIZAPI.InventoryDeviceInfoEntity[]>([]);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await inventoryDeviceInfoPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        form.resetFields();
        table.search.submit();
      }
    };
  });

  const onCancel = () => {
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  // 仅保存
  const onSave = () => {
    args?.onSuccess?.(selectedRows || []);
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  return (
    <Drawer
      title="备件"
      extra={
        <Space>
          <Button type="primary" onClick={onSave}>
            保存
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="name">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入名称"
          />
        </Filter.Item>
        <Filter.Item name="type">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入规格型号"
          />
        </Filter.Item>
        <Filter.Item name="supplier">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入供应商"
          />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '名称',
            dataIndex: 'name'
          },
          {
            title: '规格型号',
            dataIndex: 'type'
          },
          {
            title: '供应商',
            dataIndex: 'supplier'
          },
          {
            title: '数量',
            dataIndex: 'number'
          },
          {
            title: '生产站点',
            dataIndex: 'productionSite'
          },
          {
            title: '工艺段',
            dataIndex: 'productionSection'
          },
          {
            title: '设备名称',
            dataIndex: 'equipmentName'
          },
          {
            title: '设备编号',
            dataIndex: 'equipmentCode'
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        rowSelection={{
          selectedRowKeys,
          onChange: (keys: React.Key[], rows) => {
            setSelectedRowKeys(keys);
            setSelectedRows(rows);
          }
        }}
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}
    </Drawer>
  );
};

export default forwardRef(Equipment);
